package org.zoomdev.zoom.web.rendering;

import org.zoomdev.zoom.common.filter.MethodFilter;
import org.zoomdev.zoom.common.filter.impl.AlwaysAcceptMethodFilter;

import java.lang.reflect.Method;
import java.util.ArrayList;

public final class RenderingFactory {

    private final ArrayList<RenderingConfig> renderings = new ArrayList<>();

    public RenderingFactory() {

    }

    static class RenderingConfig {
        MethodFilter filter;
        Rendering rendering;

        RenderingConfig(Rendering rendering, MethodFilter methodFilter) {
            this.filter = methodFilter;
            this.rendering = rendering;
        }
    }

    public <T extends Rendering> T getRendering(Class<T> type) {
        for (RenderingConfig config : renderings) {
            if (config.rendering.getClass() == type) {
                return (T) config.rendering;
            }
        }
        return null;
    }

    public Rendering createRendering(Class<?> targetClass, Method method) {
        for (RenderingConfig config : renderings) {
            if (config.filter.accept(targetClass, method)) {
                return config.rendering;
            }
        }

        return renderings.get(renderings.size() - 1).rendering;
    }

    public void add(Rendering rendering, MethodFilter filter) {
        add(rendering, filter, renderings.size());
    }

    public void add(Rendering rendering, MethodFilter filter, int index) {
        if (index > renderings.size()) {
            index = renderings.size();
        }
        if (index < 0) {
            index = 0;
        }
        renderings.add(index, new RenderingConfig(rendering, filter));
    }

    public void add(Rendering rendering) {
        add(rendering, AlwaysAcceptMethodFilter.FILTER, renderings.size());
    }

}
